const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const OptimizeCssAssetsWebpackPlugin 
    = require('optimize-css-assets-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');

const glob = require('glob');

const HtmlWebpackExternalsPlugin = require('html-webpack-externals-plugin');

const webpack = require('webpack');

const setMPA = () => {
    const entry = {};
    const plugins = [];

    const entryFiles = glob.sync(path.join(__dirname, './src/*/index-server.js'));

    // 看视频评论后修改了一下, 使用 `Object.keys` 先处理一遍
    // 这样无论`entryFiles`是数组还是对象都能兼容下面的代码
    Object.keys(entryFiles).map( (key) => {
        const absoluteFilepath = entryFiles[key];
        const match = absoluteFilepath.match(/src\/(.*)\/index-server\.js/)
        const folderName = match && match[1];
        if (folderName) {
            entry[folderName] = absoluteFilepath;
            plugins.push(
                new HtmlWebpackPlugin({
                    template: path.join(__dirname, `src/${folderName}/index.html`),
                    filename: `${folderName}.html`,
                    chunks: [folderName, 'vendors'],
                    inject: true,
                    minify: {
                        html5: true,
                        collapseWhitespace: true,
                        preserveLineBreaks: false,
                        minifyCSS: true,
                        minifyJS: true,
                        removeComments: false
                    }
                })
            );
        }
    } );

    return {
        entry,
        plugins
    }
}

const { entry, plugins } = setMPA();

module.exports = {
    entry: entry,
    output: {
        path: path.join(__dirname, '/dist'),
        filename: '[name]-server.js',
        libraryTarget: 'umd',
    },
    mode: 'none', // production, development, none
    devtool: 'inline-source-map', // eval, source-map, inline-source-map, 
    module: {
        rules: [
            {
                test: /\.css$/,
                use: 'ignore-loader'
            },
            {
                test: /\.less$/,
                use: 'ignore-loader'
            },
        ]
    },
    plugins: [
        new MiniCssExtractPlugin({
            filename: '[name]_[contenthash:8].css'
        }),
        new OptimizeCssAssetsWebpackPlugin({
            assetNameRegExp: /\.css$/g,
            cssProcessor: require('cssnano')
        }),
        new CleanWebpackPlugin(),
        new webpack.optimize.ModuleConcatenationPlugin()
    ].concat(plugins),
    optimization: {
        splitChunks: {
            minSize: 0, // 0, 1000
            cacheGroups: {
                commons: {
                    // test: /(react|react-dom)/,
                    name: 'commons',
                    chunks: 'all',
                    minChunks: 3, // 2, 3
                }
            }
        }
    },
}
